package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	"github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	entranslations "github.com/go-playground/validator/v10/translations/en"
	zhtranslations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"regexp"
	"yak.admin/src/util"
)

//设置Translation
func TranslationMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		v := validator.New()
		// 设置支持语言
		enlang := en.New()
		zhlang := zh.New()
		// 设置国际化翻译器
		uni := ut.New(zhlang, zhlang, enlang)
		// this is usually know or extracted from http 'Accept-Language' header
		// also see uni.FindTranslator(...)
		locale := c.DefaultQuery("locale", "zh")
		trans, _ := uni.GetTranslator(locale)
		//翻译器注册到validator
		switch locale {
		case "en":
			_ = entranslations.RegisterDefaultTranslations(v, trans)
			break
		default:
			_ = zhtranslations.RegisterDefaultTranslations(v, trans)
			v.RegisterTagNameFunc(func(fld reflect.StructField) string {
				return fld.Tag.Get("chn")
			})

			_ = v.RegisterValidation("phone", phone)
			_ = v.RegisterTranslation("phone", trans, func(ut ut.Translator) error {
				return ut.Add("phone", "{0} 填写不正确哦", true)
			}, func(ut ut.Translator, fe validator.FieldError) string {
				t, _ := ut.T("phone", fe.Field())
				return t
			})

			_ = v.RegisterValidation("password", password)
			_ = v.RegisterTranslation("password", trans, func(ut ut.Translator) error {
				return ut.Add("password", "密码长度8～16位，只能包含_字母大小写及数字", true)
			}, func(ut ut.Translator, fe validator.FieldError) string {
				t, _ := ut.T("password", fe.Field())
				return t
			})
		}
		c.Set(util.ValidatorKey, v)
		c.Set(util.TranslatorKey, trans)
		c.Next()
	}
}

func phone(fl validator.FieldLevel) bool {
	mobileNum := fl.Field().String()
	fl.StructFieldName()
	regular := "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$"
	reg := regexp.MustCompile(regular)
	return reg.MatchString(mobileNum)
}

func password(fl validator.FieldLevel) bool {
	str := fl.Field().String()
	fl.StructFieldName()
	regular := "^[a-zA-Z0-9_-]{8,16}$"
	reg := regexp.MustCompile(regular)
	return reg.MatchString(str)
}

